package com.hhxy.web;

import com.hhxy.pojo.Brand;
import com.hhxy.service.BrandService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
    //细节：因为在该类中要多次使用BrandService对象所以提升作用域
    BrandService service = new BrandService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //1、获取BrandService对象
        //2、接收请求参数（用户输入的数据）
        String brandName = request.getParameter("brandName");
        String companyName = request.getParameter("companyName");
        String ordered = request.getParameter("ordered");
        String description = request.getParameter("description");
        String status = request.getParameter("status");

        //3、解决中文乱码
        //方案一：Post方式：
        //request.setCharacterEncoding("utf-8");//这行代码要放在2、的前面
        /*
        //方案二：通用方式：
        //Step1：设置编码
        byte[] bytes1 = brandName.getBytes(StandardCharsets.ISO_8859_1);
        byte[] bytes2 = companyName.getBytes(StandardCharsets.ISO_8859_1);
        byte[] bytes3 = description.getBytes(StandardCharsets.ISO_8859_1);
        //Step2：设计解码
        brandName = new String(bytes1,StandardCharsets.UTF_8);
        companyName = new String(bytes2,StandardCharsets.UTF_8);
        description = new String(bytes3,StandardCharsets.UTF_8);
        */

        //4、封装数据
        Brand brand = new Brand();
        brand.setBrandName(brandName);
        brand.setCompanyName(companyName);
        brand.setOrdered(Integer.parseInt(ordered));
        brand.setDescription(description);
        brand.setStatus(Integer.parseInt(status));
        //5、调用addService对象完成添加
        service.add(brand);
        //6、请求转发到brand.js，查看添加后的结果
        request.getRequestDispatcher("/SelectAllServlet").forward(request,response);

    }
}
